//
//  EBookListViewController.swift
//  clreader
//
//  Created by colin on 2019/3/11.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import MJRefresh

class EBookListViewController: CLBaseViewController {

    private var contentCollectionView:UICollectionView?
    private var datas = [JSONObject]()
    private var page = Router.defaultPage
    private var taskHandle:URLSessionTask?
    
    private var bookType:Int? = nil
    private var cats = [JSONObject]()
    private var catId:Int? = nil
    
    convenience init(book_type:Int? = 2) {
        self.init()
        self.bookType = book_type
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white

        //topBar
        let topBar = CLNavigationBar().then {
            $0.backHandle = { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            }
        }
        topBar.show(inView: self.view)
        
        // 列表
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout()).then {
            $0.dataSource = self
            $0.delegate = self
            $0.showsVerticalScrollIndicator = false
            $0.showsHorizontalScrollIndicator = false
            $0.backgroundColor = UIColor.clear
            $0.decelerationRate = UIScrollView.DecelerationRate.fast
            $0.register(Cell.self, forCellWithReuseIdentifier: "Cell")
            $0.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
                self?.refresh()
            })
        }
        self.contentCollectionView = collectionView

        // 判断新书速递还是电子书
        if let bookType = self.bookType, bookType == 2 {
            topBar.title = "新书速递"
            
            collectionView.mj_header?.beginRefreshing()
            self.view.addSubview(collectionView)
            collectionView.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(topBar.snp.bottom)
                make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            }
            
        } else {
            topBar.title = "电子书"
            
            //tags
            _ = Router.book_catlist.request { [weak self] (response:RequestResponse<[JSONObject]>) in
                if case .success(let successData,_) = response {
                    
                    guard let `self` = self else {return}
                    
                    var tags = ["全部"]
                    
                    if let tags_ = successData?.map({ (item) -> String in
                        if let name = item["cat_name"] as? String {
                            return name
                        } else {
                            return " "
                        }
                    }) {
                        tags = tags_
                    }
                    if let cats_ = successData {
                        self.cats = cats_
                    }
                    
                    let catView = TagsView(tags: tags)
                    catView.valueChanged = { (index) in
                        if index < self.cats.count {
                            self.catId = self.cats[index]["cat_id"] as? Int
                            self.contentCollectionView?.mj_header?.beginRefreshing()
                        }
                    }
                    self.view.addSubview(catView)
                    catView.snp.makeConstraints { (make) in
                        make.left.equalToSuperview().offset(15.0)
                        make.right.equalToSuperview().offset(-15.0)
                        make.top.equalTo(topBar.snp.bottom).offset(15.0)
                    }
                    
                    guard let collectionView_ = self.contentCollectionView else {return}
                    
                    // 默认选中第一个cat
                    if self.cats.count > 0 {
                        self.catId = self.cats[0]["cat_id"] as? Int
                    }
                    collectionView_.mj_header?.beginRefreshing()
                    
                    self.view.addSubview(collectionView_)
                    collectionView_.snp.makeConstraints { (make) in
                        make.left.right.equalToSuperview()
                        make.top.equalTo(catView.snp.bottom).offset(15.0)
                        make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
                    }
                }
                
                if case .failure(_,let message) = response {
                    self?.hud.showText(message)
                }
            }
        }
        
    }

}

extension EBookListViewController {
    
    private func refresh() {
        
        self.page = Router.defaultPage
        self.taskHandle?.cancel()
        self.contentCollectionView?.mj_footer = nil
        
        self.taskHandle =
            Router.goods_list(cat_id: self.catId, type: SourceType.电子书.intValue,book_type: self.bookType, pageNum: self.page, pageSize: Router.defaultPageSize).request { [weak self] (response:RequestResponse<JSONObject>) in
                
                self?.taskHandle = nil
                self?.contentCollectionView?.mj_header?.endRefreshing()
                
                if case .success(let successData,_) = response {
                    if let sources = successData?["rows"] as? [JSONObject] {
                        self?.page += 1
                        self?.datas = sources
                        if sources.count >= Router.defaultPageSize {
                            self?.contentCollectionView?.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
                                self?.loadMore()
                            })
                        }
                    } else {
                        self?.datas = []
                    }
                    
                    self?.contentCollectionView?.reloadData()
                }
                
                if case .failure(_,let message) = response {
                    self?.hud.showText(message)
                }
        }
    }
    
    private func loadMore() {
        
        if self.taskHandle != nil {
            return
        }

        self.taskHandle =
            Router.goods_list(cat_id: self.catId, type: SourceType.电子书.intValue, book_type: self.bookType, pageNum: self.page, pageSize: Router.defaultPageSize).request { [weak self] (response:RequestResponse<JSONObject>) in
                
                self?.taskHandle = nil
                
                if case .success(let successData,_) = response {
                    if let sources = successData?["rows"] as? [JSONObject] {
                        self?.page += 1
                        self?.datas += sources
                        if sources.count >= Router.defaultPageSize {
                            self?.contentCollectionView?.mj_footer?.endRefreshing()
                        } else {
                            self?.contentCollectionView?.mj_footer?.endRefreshingWithNoMoreData()
                        }
                    } else {
                        self?.contentCollectionView?.mj_footer?.endRefreshingWithNoMoreData()
                        self?.datas = []
                    }
                    
                    self?.contentCollectionView?.reloadData()
                }
                
                if case .failure(_,let message) = response {
                    self?.contentCollectionView?.mj_footer?.endRefreshing()
                    self?.hud.showText(message)
                }
        }
    }
}

// MARK: - UICollectionViewDataSource
extension EBookListViewController : UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.datas.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
        cell.refresh(self.datas[indexPath.item])
        return cell
    }
}

//MARK:UICollectionViewDelegateFlowLayout
extension EBookListViewController : UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let goods_id = self.datas[indexPath.item]["goods_id"] as? Int, goods_id > 0 {
            let controller = EBookDetailViewController(goods_id: goods_id)
            self.show(controller, sender: nil)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 15, left: 15, bottom:15, right: 15)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let padding = UIEdgeInsets(top: 15.0, left: 15.0, bottom: 15.0, right: 15.0)
        let ratio:CGFloat = 125.0 / 90.0
        let distance:CGFloat = 35.0
        let columnCount:CGFloat = 3.0
        let imageWidth = (UIScreen.main.bounds.width - padding.left - padding.right - (columnCount - 1) * distance) / columnCount
        let imageHeight = imageWidth * ratio
        return CGSize(width: imageWidth, height: imageHeight + 40.0)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0.0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 20.0
    }
}

extension EBookListViewController {
    class Cell: UICollectionViewCell {
        
        private lazy var imageViewPhoto = UIImageView()
        private lazy var labelName = UILabel()
        private lazy var labelPrice = UILabel()
        
        override init(frame: CGRect) {
            super.init(frame: CGRect.zero)
            self.contentView.backgroundColor = UIColor.clear
            
            self.imageViewPhoto.do {
                $0.layer.shadowColor = UIColor.black.cgColor
                $0.layer.shadowOffset = CGSize(width:2.0,height:4.0)
                $0.layer.shadowOpacity = 0.3 //阴影
            }
            self.contentView.addSubview(self.imageViewPhoto)
            self.imageViewPhoto.snp.makeConstraints { (make) in
                make.left.right.top.equalToSuperview()
                make.height.equalTo(self.contentView.snp.width).multipliedBy(125.0 / 90.0)
            }

            self.labelName.do {
                $0.textColor = UIColor(hex: "828282")
                $0.font = UIFont.systemFont(ofSize: 12.0, weight: .light)
            }
            self.contentView.addSubview(self.labelName)
            self.labelName.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(self.imageViewPhoto.snp.bottom).offset(5.0)
            }
            
            self.labelPrice.do {
                $0.textColor = UIColor(hex: "343434")
                $0.font = UIFont.systemFont(ofSize: 12.0, weight: .light)
            }
            self.contentView.addSubview(self.labelPrice)
            self.labelPrice.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(self.labelName.snp.bottom).offset(5.0)
            }
            
        }
        
        func refresh(_ data:JSONObject?) {
            self.labelName.text = data?["title"] as? String
            
            // 价格
            if let price = data?["price"] as? Double {
                self.labelPrice.text = "¥\(price)"
            } else {
                self.labelPrice.text = ""
            }
            
            // 图片
            if let cover_url = data?["cover_url"] as? String,!cover_url.isEmpty,
                let baseUrl = URL(string: Router.baseUrl) {
                let imageUrl = baseUrl.appendingPathComponent(cover_url)
                self.imageViewPhoto.kf.setImage(with: imageUrl)
            } else {
                self.imageViewPhoto.image = nil
            }
            
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}

// MARK - 头部标签
extension EBookListViewController {
    
    class TagsView: UIView {
        
        var selectedIndex:Int {
            return self.index
        }
        
        var valueChanged:((_ select:Int)->Void)?
        
        private var tags = [String]()
        private var items = [UIView]()
        private var titles = [UILabel]()
        
        private var index = 0
        
        init(tags:[String]) {
            super.init(frame: CGRect.zero)
            self.tags = tags
            self.initViews()
        }
        
        func initViews() {
            self.backgroundColor = UIColor.white
            
            var x:CGFloat = 0
            var y:CGFloat = 0
            var containerHeight:CGFloat = 0
            let containerWidth = UIScreen.main.bounds.width - 15.0 - 15.0
            let itemHeight:CGFloat = 30.0
            let distance:CGFloat = 10.0
            let paddingH:CGFloat = 10.0
            
            for index in 0 ..< self.tags.count {
                
                let item = UIView().then {
                    $0.backgroundColor = UIColor(hex: "EFEFEF")
                    $0.layer.cornerRadius = 5.0
                    $0.layer.masksToBounds = true
                    $0.tag = index
                    $0.isUserInteractionEnabled = true
                    let tap = UITapGestureRecognizer(target: self, action: #selector(self.actionTap(ges:)))
                    $0.addGestureRecognizer(tap)
                    
                    let labelTag = UILabel().then {
                        $0.text = tags[index]
                        $0.textColor = UIColor(hex: "343434")
                        $0.font = UIFont.systemFont(ofSize: 14.0, weight: .light)
                    }
                    $0.addSubview(labelTag)
                    labelTag.snp.makeConstraints({ (make) in
                        make.left.equalToSuperview().offset(paddingH)
                        make.right.equalToSuperview().offset(-paddingH)
                        make.centerY.equalToSuperview()
                    })
                    
                    self.titles.append(labelTag)
                    if index == self.index {
                        labelTag.textColor = UIColor.white
                    }
                }
                self.addSubview(item)
                
                self.items.append(item)
                if index == self.index {
                    item.backgroundColor = UIColor(hex: "AE1600")
                }
                
                // 计算当前的位置
                let currentWidth = tags[index].size(font: UIFont.systemFont(ofSize: 14.0, weight: .light), containerWidth: CGFloat.greatestFiniteMagnitude).width + paddingH + paddingH
                if x == 0 && y == 0 {
                    containerHeight += itemHeight
                }
                if x + currentWidth + distance > containerWidth {
                    // 容器高度
                    containerHeight += itemHeight + distance
                    
                    // 需要换行
                    x = 0
                    y += itemHeight + distance
                }
                
                item.snp.makeConstraints({ (make) in
                    make.left.equalToSuperview().offset(x)
                    make.top.equalToSuperview().offset(y)
                    make.height.equalTo(itemHeight)
                    
                    if index == self.tags.count - 1 {
                        make.bottom.equalToSuperview()
                    }
                    
                })
                
                // 计算下一个的位置
                if x + currentWidth + distance > containerWidth {
                    // 需要换行
                    x = 0
                    y += itemHeight + distance
                } else {
                    x += currentWidth + distance
                }
            }
            
        }
        
        @objc private func actionTap(ges:UIGestureRecognizer) {
            if let index_ = ges.view?.tag, index_ != self.index {
                // 选中index_
                if index_ < self.items.count {
                    self.items[index_].backgroundColor = UIColor(hex: "AE1600")
                }
                if index_ < self.titles.count {
                    self.titles[index_].textColor = UIColor.white
                }
                
                // 反选
                if self.index < self.items.count {
                    self.items[self.index].backgroundColor = UIColor(hex: "efefef")
                }
                if self.index < self.titles.count {
                    self.titles[self.index].textColor = UIColor(hex: "343434")
                }
                
                self.index = index_
                self.valueChanged?(self.index)
            }
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
    }
    
}
